package com.honeywen.mymvc.leetcode;

/**
 * 122. 买卖股票的最佳时机 II
 * https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
 *
 * @author wangwei
 * @date 2019/4/8
 */
public class MaxProfit {

    private static int[] a1 = {7, 1, 5, 3, 6, 4};
    private static int[] a2 = {1, 2, 3, 4, 5};
    private static int[] a3 = {7, 6, 4, 3, 1};

    public static void main(String[] args) {
        System.out.println(maxProfit(a1));
        System.out.println(maxProfit(a2));
        System.out.println(maxProfit(a3));

        System.out.println(maxProfit2(a1));
        System.out.println(maxProfit2(a2));
        System.out.println(maxProfit2(a3));

        System.out.println(maxProfit3(a1));
        System.out.println(maxProfit3(a2));
        System.out.println(maxProfit3(a3));


    }


    public static int maxProfit3(int[] prices) {
        // 赚钱就卖

        int max = 0;
        for (int i = 0, len = prices.length; i < len - 1; i++) {
            max += (Math.max(0, prices[i + 1] - prices[i]));

        }

        return max;

    }


    public static int maxProfit2(int[] prices) {

        // 寻找买入条件
        // 阶段低点
        // 寻找阶段低点，前面后面比当前高，
        int max = 0;
        int len = prices.length;
        boolean buy = false;
        int buyIndex = -1;
        for (int i = 0; i < len - 1; i++) {
            // 买
            if (prices[i] < prices[i + 1] && !buy) {
                buy = true;
                buyIndex = i;
            }

            // 卖
            if (prices[i] > prices[i + 1] && buy) {
                buy = false;
                max += (prices[i] - prices[buyIndex]);
            }

        }


        if (buy) {
            max += (prices[len - 1] - prices[buyIndex]);
        }

        return max;
    }

    public static int maxProfit(int[] prices) {


        int max = 0;
        int low = -1;
        int len = prices.length;
        for (int i = 0; i < len - 1; i++) {
            if (prices[i] < prices[i + 1] && low < 0) {
                low = i;
            }
            if (prices[i] > prices[i + 1] && low >= 0) {
                max += (prices[i] - prices[low]);
                low = -1;
            }
        }

        if (low >= 0) {
            max += (prices[len - 1] - prices[low]);
        }

        return max;

    }

}
